<template>
  <div class="base-container">
    <t-form
      ref="form"
      :data="queryParams"
      label-width="80"
      @submit="
        () => {
          this.pagination.current = 1;
          this.queryParams.pageNum = 1;
          this.getList();
        }
      "
      @reset="
        () => {
          this.pagination.current = 1;
          this.queryParams.pageNum = 1;
          this.getList();
        }
      "
    >
      <t-row style="border-bottom: 1px solid #e5e6eb; margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="软件名称" name="name">
            <t-input v-model="queryParams.name" clearable placeholder="请输入软件名称" style="width: 240px" />
          </t-form-item>
          <t-form-item label="开发完成日期" name="completeDevelopmentDateRange">
            <t-date-range-picker
              style="width: 280px"
              :placeholder="['开始时间', '结束时间']"
              v-model="queryParams.completeDevelopmentDateRange"
              allow-input
              clearable
            />
          </t-form-item>
          <t-form-item label="首次发表日期" name="firstPublicationDateRange">
            <t-date-range-picker
              style="width: 280px"
              :placeholder="['开始时间', '结束时间']"
              v-model="queryParams.firstPublicationDateRange"
              allow-input
              clearable
            />
          </t-form-item>
          <t-form-item label="权利取得方式" name="getWay">
            <t-select style="width: 240px" clearable v-model="queryParams.getWay" :options="dict.type.get_way">
            </t-select>
          </t-form-item>
          <t-form-item label="权利范围" name="getWay">
            <t-select
              clearable
              multiple
              style="width: 240px"
              :options="ScopeRightsOptions"
              v-model="queryParams.scopeRightsList"
            >
            </t-select>
          </t-form-item>
          <t-form-item label="登记号" name="registerNum">
            <t-input v-model="queryParams.registerNum" clearable placeholder="请输入登记号" style="width: 240px" />
          </t-form-item>
          <t-form-item label="填报单位" name="declareDeptName">
            <t-input
              v-model="queryParams.declareDeptName"
              clearable
              placeholder="请输入填报单位"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="参与人员" name="peopleName">
            <t-input v-model="queryParams.peopleName" clearable style="width: 240px" />
          </t-form-item>
          <!-- <t-form-item label="软著状态" name="softwareCopyrightStatus">
            <t-select  style="width: 240px" clearable v-model="queryParams.softwareCopyrightStatus"
                       :options="dict.type.achievement_status">
            </t-select>
          </t-form-item> -->
          <t-form-item label="子系统名称" name="serviceCode">
            <t-select
              clearable
              v-model="queryParams.serviceCode"
              :keys="{ label: 'serviceName', value: 'serviceCode' }"
              style="width: 240px"
              :options="serviceOptions"
            ></t-select>
          </t-form-item>
          <t-form-item label="项目名称" name="businessId">
            <t-select
              :disabled="queryParams.serviceCode === ''"
              @search="remoteProject"
              placeholder="请先选择子系统后搜索"
              v-model="queryParams.businessId"
              style="width: 240px"
              filterable
              clearable
              :keys="{ label: 'businessName', value: 'businessId' }"
              :options="projectOptions"
            >
            </t-select>
          </t-form-item>
          <t-form-item label="外部项目名称" name="businessName">
            <t-input v-model="queryParams.businessName" clearable style="width: 240px" />
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon" />
        录入
      </t-button>
    </div> -->
    <t-table rowKey="id" :data="data" :columns="columns" hover :pagination="pagination" :loading="dataLoading">
      <template #name="{ row }">
        <t-link
          @click="
            dialog.objId = row.id;
            dialog.header = row.name;
            dialog.open_review = true;
          "
          hover="color"
          theme="primary"
          >{{ row.name }}</t-link
        >
      </template>
      <template #copyrightMemberList="{ row }">
        <template v-for="(item, index) in row.copyrightMemberList">
          {{ item.name
          }}{{ index + 1 === row.copyrightMemberList.length && row.copyrightCompanyList.length <= 0 ? '' : '、' }}
        </template>
        <template v-for="(item, index) in row.copyrightCompanyList">
          {{ item.company }}{{ index + 1 === row.copyrightCompanyList.length ? '' : '、' }}
        </template>
      </template>
      <template #copyrightProjectList="{ row }">
        <template v-for="(item, index) in row.copyrightProjectList">
          {{ item.businessName }}{{ index + 1 === row.copyrightProjectList.length ? '' : '、' }}
        </template>
      </template>
      <template #getWay="{ row }">
        {{ row.getWay | filterByDict(dict.type.get_way) }}
      </template>
      <template #scopeRights="{ row }">
        {{ row.scopeRights | filterByDict(dict.type.scope_rights, '全部权利') }}
      </template>

      <template #softwareCopyrightStatus="{ row }">
        <t-tag
          @click="
            dialog.header = row.name;
            dialog.objId = row.id;
            dialog.open_approve_list = true;
          "
          class="cursor-pointer"
          :theme="handleTheme(row.softwareCopyrightStatus, dict.type.achievement_status)"
          variant="light"
        >
          {{ row.softwareCopyrightStatus | filterByDict(dict.type.achievement_status) }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <!--        v-if="['1','4',null].includes(row.softwareCopyrightStatus)"-->
        <t-button
          @click="updateData(row)"
          size="small"
          variant="text"
          class="t-button-link"
          v-if="row.createUserId === Number($store.state.user.userId)"
        >
          <t-icon name="edit-1" slot="icon" />
          继续录入
        </t-button>
        <t-button
          size="small"
          @click="
            dialog.objId = row.id;
            dialog.header = row.name;
            dialog.open_detail = true;
          "
          variant="text"
          class="t-button-link"
        >
          <t-icon name="info-circle" slot="icon" />
          详情
        </t-button>
        <!--        ['1','4',null].includes(row.softwareCopyrightStatus)  &&-->
        <t-button
          v-if="row.createUserId === Number($store.state.user.userId)"
          theme="danger"
          @click="delObj(row)"
          size="small"
          variant="text"
          class="t-button-link"
        >
          <t-icon name="delete" slot="icon" />
          删除
        </t-button>
      </template>
    </t-table>
    <copyright-detail-dialog
      :objId="dialog.objId"
      :header="dialog.header"
      :visible.sync="dialog.open_detail"
      v-if="dialog.open_detail"
    >
    </copyright-detail-dialog>
    <file-review
      :header="dialog.header"
      achievementType="4"
      :visible.sync="dialog.open_review"
      v-if="dialog.open_review"
      :objId="dialog.objId"
    ></file-review>
  </div>
</template>

<script>
import copyrightDetailDialog from './components/copyright-detail-dialog.vue';
import fileReview from '../components/file-review.vue';

export default {
  name: 'copyright-my',
  dicts: ['get_way', 'scope_rights', 'achievement_status'],
  components: {
    copyrightDetailDialog,
    fileReview,
  },
  data() {
    return {
      dialog: {
        header: '',
        open: false,
        objId: null,
        open_approve_list: false,
        open_detail: false,
        open_review: false,
      },
      serviceOptions: [],
      projectOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        completeDevelopmentDate: '',
        completeDevelopmentDateRange: [],
        startCompleteDevelopmentDate: '',
        endCompleteDevelopmentDate: '',
        firstPublicationDate: '',
        firstPublicationDateRange: [],
        startFirstPublicationDate: '',
        endFirstPublicationDate: '',
        getWay: '',
        scopeRights: '',
        registerNum: '',
        declareDeptName: '',
        softwareCopyrightStatus: '',
        scopeRightsList: [],
        peopleName: '',
        businessName: '',
        status: '',
        dateRange: [],
        serviceCode: '',
        businessId: null,
      },
      data: [],
      columns: [
        {
          colKey: 'name',
          title: '软件名称',
          align: 'center',
        },
        // {
        //   colKey: "copyrightName",
        //   title: "著作权人",
        //   align: "center"
        // },
        {
          colKey: 'completeDevelopmentDate',
          title: '开发完成日期',
          align: 'center',
        },
        {
          colKey: 'firstPublicationDate',
          title: '首次发表日期',
          align: 'center',
        },
        {
          colKey: 'getWay',
          title: '权利取得方式',
          align: 'center',
        },
        {
          colKey: 'scopeRights',
          title: '权利范围',
          align: 'center',
        },
        {
          colKey: 'registerNum',
          title: '登记号',
          align: 'center',
        },
        // {
        //   colKey: "declareDeptName",
        //   title: "填报单位",
        //   align: "center"
        // },
        {
          colKey: 'copyrightMemberList',
          title: '著作权人',
          align: 'center',
        },
        {
          colKey: 'declareDeptName',
          title: '填报单位',
          align: 'center',
        },
        {
          colKey: 'copyrightProjectList',
          title: '项目来源',
          align: 'center',
        },
        // {
        //   colKey: "createTime",
        //   title: "创建时间",
        //   align: "center"
        // },
        // {
        //   colKey: "softwareCopyrightStatus",
        //   title: "软著状态",
        //   align: "center",
        //   fixed: 'right'
        // },
        {
          colKey: 'op',
          title: '操作',
          align: 'center',
          width: 140,
        },
      ],
      dataLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination, pageInfo);
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList();
        },
      },
    };
  },
  computed: {
    ScopeRightsOptions() {
      let n;
      if (this.dict.type.scope_rights) {
        n = [{ label: '全部权利', checkAll: true }].concat(this.dict.type.scope_rights);
      }
      return n;
    },
  },
  created() {
    Object.assign(this.queryParams, this.handelQuery(this.queryParams, this.$route.query));
    if (this.queryParams.businessId) {
      this.remoteProject(this.queryParams.projectName);
    }
    this.getSysServices();
    this.getList();
  },
  methods: {
    apply() {
      this.$router.push(`/cgzh/other/copyright/copyright-apply/${Date.parse(new Date())}`);
    },
    updateData(row) {
      sessionStorage.removeItem(`${row.id}-copyright-activeForm`);
      const taskId = row.id;
      const activeFormList = [];
      this.$api.cgzh.copyright
        .getAll(row.id)
        .then((response) => {
          sessionStorage.removeItem(`${taskId}-copyright-copyrightId`);
          if (response.data.id) {
            sessionStorage.setItem(`${taskId}-copyright-copyrightId`, response.data.id);
          } else {
            activeFormList.push(0);
          }
          if (
            (response.data.copyrightMemberList && response.data.copyrightMemberList.length > 0) ||
            (response.data.copyrightCompanyList && response.data.copyrightCompanyList.length > 0)
          ) {
            sessionStorage.setItem(`${taskId}-copyright-memberId`, response.data.copyrightMemberList.length);
          } else {
            activeFormList.push(1);
          }
          if (response.data.copyrightBenefitList && response.data.copyrightBenefitList.length > 0) {
            sessionStorage.setItem(`${taskId}-copyright-benefitId`, response.data.copyrightBenefitList.length);
          } else {
            activeFormList.push(2);
          }
          if (response.data.copyrightProjectList && response.data.copyrightProjectList.length > 0) {
            sessionStorage.setItem(`${taskId}-copyright-projectId`, response.data.copyrightProjectList.length);
          } else {
            activeFormList.push(3);
          }
          if (activeFormList.length <= 0) {
            sessionStorage.setItem(`${taskId}-copyright-activeForm`, 4); // 跳转到最后一步
          } else {
            sessionStorage.setItem(`${taskId}-copyright-activeForm`, activeFormList[0]); // 跳转到第一个不满足
          }
          this.$router.push({
            path: `/cgzh/other/copyright/copyright-apply/${row.id}`,
            query: { title: `软著录入-${row.name}` },
          });
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    remoteProject(search) {
      this.$api.cgzh
        .getProjectByServiceCode({
          serviceCode: this.queryParams.serviceCode,
          // businessId: this.queryParams.businessId,
          projectName: search,
        })
        .then((response) => {
          response.data.forEach((val2) => {
            const index = this.projectOptions.findIndex((val) => val.businessId === val2.businessId);
            if (index === -1) {
              this.projectOptions.push(val2);
            }
          });
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    getSysServices() {
      this.$api.cgzh
        .getSysServices()
        .then((response) => {
          this.serviceOptions = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    getList() {
      this.dataLoading = true;
      [this.queryParams.startCompleteDevelopmentDate, this.queryParams.endCompleteDevelopmentDate] =
        this.queryParams.completeDevelopmentDateRange;
      [this.queryParams.startFirstPublicationDate, this.queryParams.endFirstPublicationDate] =
        this.queryParams.firstPublicationDateRange;
      [this.queryParams.scopeRights] = this.queryParams.scopeRightsList.join(',');
      this.$api.cgzh.copyright
        .myList(this.queryParams)
        .then((response) => {
          this.data = response.rows;
          this.pagination.total = response.total;
          this.dataLoading = false;
        })
        .catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });
    },
    delObj(row) {
      const confirmDia = this.$dialog.confirm({
        header: '系统提示',
        body: `是否确认删除软件名称为"${row.name}"的数据项？`,
        theme: 'warning',
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          });
          this.$api.cgzh.copyright
            .delete(row.id)
            .then((res) => {
              this.getList();
              this.$message.success('删除成功');
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            })
            .catch((e) => {
              confirmDia.update({
                confirmBtn: {
                  loading: false,
                },
              });
              this.$message.error(e.toString());
            });
        },
      });
    },
  },
};
</script>

<style scoped></style>
